// ============================================================================
// Name : FileSchemeScanner.java
// Author : iron.yin@gmail.com
// Version : v1.0
// Copyright : RisingSun CO,.LTD
// Description : FileSchemeScanner.java in Java
// ============================================================================
package cc.risingsun.wing.core.scanner;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.Set;

import cc.risingsun.wing.core.util.Closing;
import cc.risingsun.wing.ds.DataStruct;

/**
 * 文件scheme扫描器
 * 
 * @author iron.yin@gmail.com
 */
public class FileSchemeScanner implements UriSchemeScanner {

	@Override
	public Set<String> getSchemes() {
		return DataStruct.singleton("file");
	}

	@Override
	public void scan(URI uri, ScannerListener listener) {
		final File file = new File(uri.getPath());
		if (file.isDirectory()) {
			// scan directory
			scanDirectoty(file, listener);
		} else {
			// log .
		}
	}

	private void scanDirectoty(final File file, final ScannerListener listener) {
		for (final File child : file.listFiles()) {
			if (child.isDirectory())
				scanDirectoty(child, listener);
			else if (listener.onAccept(child.getName())) {
				try {
					new Closing(new BufferedInputStream(new FileInputStream(child))).invoke(new Closing.Closure() {
						@Override
						public void fun(InputStream input) throws IOException {
							listener.onProcess(child.getName(), input);
						}
					});
				} catch (IOException e) {
					throw new ScannerException("IO error when scanning file "
							+ child, e);
				}
			}
		}
	}
}
